package web;

import com.alibaba.fastjson.JSON;
import dao.User;
import tools.RandomStr;
import utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static tools.InfoPack.RstoJson;

public class UserInfoServlet extends BaseServlet{



    public void nomarlCard(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("normalcardServlet 已经启动");
        resp.setContentType("application/json;charset=UTF-8");

        String userNum = "";

        Cookie[] cookies = req.getCookies();
        for(Cookie cookie:cookies) {
            System.out.println(cookie.getName() + " " + cookie.getValue());
            if("userNum".equals(cookie.getName())) {
                userNum = cookie.getValue();
            }
        }
        User user = new User();






        // 数据库调用相关
        Connection connection = null;
        PreparedStatement pStatement = null;
        ResultSet rsSet = null;

        // 连接数据库
        connection = JDBCUtils.getConnection();

        String sql = "select * from student where userNum = ?";

        try {
            pStatement = connection.prepareStatement(sql);
            pStatement.setString(1, userNum );
            rsSet = pStatement.executeQuery();



            if(rsSet.next()) {

                user.setUserNum(userNum);
                user.setUserName(rsSet.getString("userName"));
                user.setUserFac(rsSet.getString("userFac"));
                user.setUserMaj(rsSet.getString("userMaj"));
                user.setUserCla(rsSet.getString("userCla"));
                user.setUserSex(rsSet.getString("userSex"));
                user.setUserBir(rsSet.getString("userBir"));
                user.setUserSta(rsSet.getString("userSta"));
                user.setUserAds(rsSet.getString("userAds"));
                user.setUserTel(rsSet.getString("userTel"));
                System.out.println(JSON.toJSONString(user));
                resp.getWriter().append(JSON.toJSONString(user));
            } else {

                resp.getWriter().append("false");
                System.out.println("用户名不存在失败");
            }

            // 然后将这个用户发给前端
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, pStatement,rsSet);	// 关闭连接
        }

    }

    // 呈交修改
    public void userInfoUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Connection connection = null;
        PreparedStatement pStatement = null;


        try {
            String sql = "UPDATE student SET userName = ?, userSex = ?, userFac = ?, userMaj = ?, userCla = ?, userBir = ?, userTel = ?, userAds = ?, userSta = ? WHERE (userNum = ?)";
            connection = JDBCUtils.getConnection();
            pStatement = connection.prepareStatement(sql);
//            String b = req.getParameter("userName");
//            String a = ISOtoUTF8(req.getParameter("userName"));
//            System.out.println(a);
            pStatement.setString(1,req.getParameter("userName"));
            pStatement.setString(2,req.getParameter("userSex"));
            pStatement.setString(3,req.getParameter("userFac"));
            pStatement.setString(4,req.getParameter("userMaj"));
            pStatement.setString(5,req.getParameter("userCla"));
            pStatement.setString(6,req.getParameter("userBir"));
            pStatement.setString(7,req.getParameter("userTel"));
            pStatement.setString(8,req.getParameter("userAds"));
            pStatement.setString(9,req.getParameter("userSta"));
            pStatement.setString(10,req.getParameter("userNum"));
            int count = pStatement.executeUpdate();
            if( count > 0) {
                System.out.println("修改成功");
                resp.getWriter().append("true");
//                resp.sendRedirect("/webdemo2/views/loginDemo.html");	// 改变地址栏 重定向
//				 req.getRequestDispatcher("/").forward(req, resp);		// 不会改变地址栏，传递请求
            }
            else {
                System.out.println("修改失败");
                resp.getWriter().append("false");

//                req.setAttribute("msg", "注册失败");
//                req.getRequestDispatcher("/Testfirst/views/fails.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("数据库插入失败");
            e.printStackTrace();
            resp.getWriter().append("false");
//            req.getRequestDispatcher("/views/fails.jsp").forward(req, resp);
        } catch (NullPointerException e) {
            // TODO: handle exception
            System.out.println("信息不完整");
            req.setAttribute("msg", "注册失败,信息填写不完整");
            resp.getWriter().append("false");
//            req.getRequestDispatcher("/views/fails.jsp").forward(req, resp);
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, pStatement);
        }
    }

    public void manageList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 数据库调用相关
        Connection connection = null;
        PreparedStatement pStatement = null;
        ResultSet rsSet = null;

        // 连接数据库
        connection = JDBCUtils.getConnection();

        String sql = "select userName,userNum,userBir, userFac ,userMaj , userCla , date_format(userBir,'%m-%d') as userBir , userTel from student";

        try {
            pStatement = connection.prepareStatement(sql);
            rsSet = pStatement.executeQuery();



            if(rsSet.next()) {
                System.out.println("用户列表获取成功");
//                System.out.println(RstoJson(rsSet));
//                resp.getWriter().append("cccc");
                resp.getWriter().append(RstoJson(rsSet));
            } else {
                resp.getWriter().append("false");
                System.out.println("用户列表获取失败");
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, pStatement,rsSet);	// 关闭连接
        }

    }

    public void userRemove (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 数据库调用相关
        Connection connection = null;
        PreparedStatement pStatement = null;
        ResultSet rsSet = null;

        // 连接数据库
        connection = JDBCUtils.getConnection();

        String sql = "select userPwd from student where userNum = ? and userPwd = ?";
        try {
            pStatement = connection.prepareStatement(sql);
            pStatement.setString(1, req.getParameter("userNum") );
            pStatement.setString(2, req.getParameter("userPwd") );
            rsSet = pStatement.executeQuery();




            if(rsSet.next()) {

                // 执行注销
                sql = "DELETE FROM student WHERE (userNum = ?)";
                pStatement = connection.prepareStatement(sql);
                pStatement.setString(1,req.getParameter("userNum"));

                pStatement.executeUpdate();

                Cookie[] cookies=req.getCookies();
                for(Cookie cookie: cookies){
                    cookie.setMaxAge(0);
                    resp.addCookie(cookie);
                }

                resp.getWriter().append("true");
            } else {
                resp.getWriter().append("false");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, pStatement,rsSet);	// 关闭连接
        }
    }

    public void userRepwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  {
        Connection connection = null;
        PreparedStatement pStatement = null;

        String userNum = req.getParameter("userNum");
        String userPwd = RandomStr.RandomPwd();     // 生成随机6位密码

        try {
            String sql = "UPDATE student SET userPwd = ? WHERE (userNum = ?)";
            connection = JDBCUtils.getConnection();
            pStatement = connection.prepareStatement(sql);
//            String b = req.getParameter("userName");
//            String a = ISOtoUTF8(req.getParameter("userName"));
//            System.out.println(a);
            pStatement.setString(1,userPwd);
            pStatement.setString(2,userNum);
            int count = pStatement.executeUpdate();
            if( count > 0) {
                System.out.println("修改成功");
                resp.getWriter().append(userPwd);
//                resp.sendRedirect("/webdemo2/views/loginDemo.html");	// 改变地址栏 重定向
//				 req.getRequestDispatcher("/").forward(req, resp);		// 不会改变地址栏，传递请求
            }
            else {
                System.out.println("修改失败");
                resp.getWriter().append("false");

//                req.setAttribute("msg", "注册失败");
//                req.getRequestDispatcher("/Testfirst/views/fails.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("数据库插入失败");
            e.printStackTrace();
            resp.getWriter().append("false");
//            req.getRequestDispatcher("/views/fails.jsp").forward(req, resp);
        } catch (NullPointerException e) {
            // TODO: handle exception
            System.out.println("信息不完整");
            req.setAttribute("msg", "注册失败,信息填写不完整");
            resp.getWriter().append("false");
//            req.getRequestDispatcher("/views/fails.jsp").forward(req, resp);
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, pStatement);
        }
    }
}

